package com.linkai.多线程._01_Thread_Runnable;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;

/**
 * @Description: 继承 Thread 类，重写 run() 方法，调用 start 开启线程
 *                注意：线程开启不一定立即执行，由 CPU 执行
 *
 *                多线程同步下载
 * @Author: 林凯
 * @Date: 2021/10/19 16:01
 */
public class TestThread2 extends Thread {

    private String url;
    private String name;    // 保存的文件名

    public TestThread2(String url, String name) {
        this.url = url;
        this.name = name;
    }

    @Override
    public void run() {
        WebDownload webDownload = new WebDownload();
        webDownload.downloader(url, name);
        System.out.println("success" + name);
    }

    public static void main(String[] args) {
        TestThread2 testThread1 = new TestThread2("https://public-cdn.mokahr.com/54fc4e3d-b42b-461a-9250-f3695e9bce98.jpg", "1.jpg");
        TestThread2 testThread2 = new TestThread2("https://public-cdn.mokahr.com/54fc4e3d-b42b-461a-9250-f3695e9bce98.jpg", "2.jpg");
        TestThread2 testThread3 = new TestThread2("https://public-cdn.mokahr.com/54fc4e3d-b42b-461a-9250-f3695e9bce98.jpg", "3.jpg");

        // 调用 start() 方法开启线程
        testThread1.start();
        testThread2.start();
        testThread3.start();

        /*
            success1.jpg
            success3.jpg
            success2.jpg
        * */

    }
}

// 下载器
class WebDownload {

    public void downloader(String url, String name) {
        try {
            FileUtils.copyURLToFile(new URL(url), new File(name));

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
